<?php

namespace Application\Controllers;

use Application\Models\BookCategory;
use GuzzleHttp\Client;
use Phalcon\Mvc\Controller;

/**
 * Class YoudaoController
 * @package Application\Controllers
 */
class YoudaoController extends Controller
{
    use \Application\Controllers\Controller;
    const BASEURL = "https://note.youdao.com";
    const KEY = "399b8f08ede51a90270743bd967f2a8b";
    const SECRET = "019b24f8834a43cb982a0edf95d66f12";
    const DOMAIN = "http://www.mirchen.com";    //不要有结尾字符 "/"
    const OAUTH_URL = "/oauth/authorize2";
    const GET_ACCESSTOKEN_URL = "/oauth/access2";
    const GET_USER_URL = "/yws/open/user/get.json?oauth_token=";
    const GET_NOTES_URL = "/yws/open/notebook/all.json";    //取得所有笔记本API
    const GET_NOTELIST_URL = "/yws/open/notebook/list.json";
    const GET_NOTE_DETAIL_URL = "/yws/open/note/get.json";
    const DOWNLOAD_FILEORIMAGE_URL = "/yws/open/resource/download/";
    const UPDATE_DETAIL_URL = "/yws/open/note/update.json";

    public static $ACCESS_TOKEN = null;
    /**
     * @var \GuzzleHttp\Client
     */
    public $guzzle = null;

    public function beforeExecuteRoute()
    {
        die("有道不支持返回MarkDown文章,放弃开发");
        if (!$this->session->isStarted()) {
            $this->session->start();
        }
        $actionName = $this->dispatcher->getActionName();
        if ($actionName != 'login' && !$this->session->has('access_token')) {
            return $this->response->redirect('/youdao/login');
        } else {
            self::$ACCESS_TOKEN = $this->session->get('access_token');
        }

        $this->guzzle = new Client([
            'base_uri' => self::BASEURL,
            'verify' => false,
        ]);
    }

    public function loginAction()
    {
        if ($this->request->get('state') === 'state' && $code = $this->request->get('code')) {  //回跳
            $accessToken = $this->getAccessToken();
            if (!$accessToken) {
                return $this->response->setContent('无法获取AccessToken');
            }
            $this->session->set('access_token', $accessToken);
            return $this->response->redirect('/youdao/index');
        } else {
            return $this->response->redirect($this->getToAuthUrl());
        }
    }

    /**
     * 自动导入到kancloud里
     */
    public function indexAction()
    {
        if (!$this->session->has('note_books')) {
            $res = \GuzzleHttp\json_decode($this->guzzle->post(self::GET_NOTES_URL, [
                'form_params' => [
                    'oauth_token' => self::$ACCESS_TOKEN
                ]
            ])->getBody()->getContents(), true);
            if (is_array($res)) {
                $this->session->set('note_books', $res);
            }
        }
        $youdaoId = 120;
        $notes = $this->session->get('note_books');
        foreach ($notes as $note) {
            $kancloudCategory = BookCategory::findFirst(['y_path="' . $note['path'] . '"']);
            if (!$kancloudCategory) {
                $kancloudCategory = new BookCategory();
            }
            $kancloudCategory->name = $note['name'];
            $kancloudCategory->y_path = $note['path'];
            $kancloudCategory->pid = $youdaoId;
            $kancloudCategory->url = $note['path'];
            $kancloudCategory->keywords = $kancloudCategory->description = '来源有道';
            $kancloudCategory->save();
            //取得笔记路径
            $list = $this->getNoteList($note['path']);
            if (!$list)  {
                continue;
            }
            foreach ($list as $path) {
                $this->getNoteDetail($path);
            }
        }
    }


    public function getNoteList($y_path)
    {
        $res = \GuzzleHttp\json_decode($this->guzzle->post(self::GET_NOTELIST_URL, [
            'form_params' => [
                'oauth_token' => self::$ACCESS_TOKEN,
                'notebook' => $y_path
            ]
        ])->getBody()->getContents(),true);
        return $res;
    }

    public function getNoteDetail($y_note_path){
        $res = \GuzzleHttp\json_decode($this->guzzle->post(self::GET_NOTE_DETAIL_URL, [
            'form_params' => [
                'oauth_token' => self::$ACCESS_TOKEN,
                'path' => $y_note_path
            ]
        ])->getBody()->getContents(),true);
        dd($res);
    }

    private function getToAuthUrl()
    {
        return self::BASEURL . self::OAUTH_URL . '?' . http_build_query([
                'client_id' => self::KEY,
                'response_type' => 'code',
                'redirect_uri' => $this->url->get('/Youdao/login'),
                'state' => 'state',
                'display' => 'web'
            ]);
    }

    private function getAccessToken()
    {
        $res = $this->guzzle->request('GET', self::GET_ACCESSTOKEN_URL, [
            'query' => [
                'client_id' => self::KEY,
                'client_secret' => self::SECRET,
                'grant_type' => 'authorization_code',
                'redirect_uri' => $this->url->get('/Youdao/index'),
                'code' => $this->request->get('code')
            ]
        ]);
        if ($content = $res->getBody()->getContents()) {
            return \GuzzleHttp\json_decode($content, true)['access_token'];
        } else {
            return null;
        }
    }
}